package code.servlet;

import code.entity.Location;
import code.service.LocationService;
import code.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: cheny
 * Date: 12-1-4
 * Time: 下午7:49
 */
public class ClientServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        super.init();
        System.out.println("ClientServlet init ......................");
        //new ServerThread().start();
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("ClientServlet Execute doget at " + new Date());
        resp.getWriter().print("ok");
        print(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("ClientServlet Execute dopost at " + new Date());
        resp.getWriter().print("ok");
        print(req, resp);
    }

    private void print(HttpServletRequest request, HttpServletResponse response) {
        Connection con=null;
        try {
            String lng = request.getParameter("lng");
            String lat = request.getParameter("lat");
            String username = request.getParameter("username");
            System.out.println("username=" + username + ",lng=" + lng + ",lat=" + lat);
            con = DBUtil.getConn(true);
            Location location = new Location();
            location.setUsername(username);
            location.setLat(lat);
            location.setLng(lng);
            location.setCreateTime(new Date());
            LocationService.saveLocation(con,location);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeConn(con);
        }
    }
}
